package com.royal.lr.util;

import javax.xml.soap.*;
import java.io.ByteArrayInputStream;
import java.util.*;

public class SoapUtil {
    /**
     * 将webservice 的返回值各个元素存储到map中
     * @param res
     * @return
     */
    public static Map<String,Object> doSoapToXml(String res){
        if(res==null) return null;
        Map<String,Object> map=new HashMap<>();
        try {
            MessageFactory messageFactory = MessageFactory.newInstance();
            SOAPMessage reqMsg = messageFactory.createMessage(
                    new MimeHeaders(),
                    new ByteArrayInputStream(res.getBytes("UTF-8")));
            reqMsg.saveChanges();
            SOAPBody soapBody= reqMsg.getSOAPBody();
            serialXml(soapBody,map);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return map;
    }

    /**
     * 将soap中获取的元素转为list
     * @return
     */
    public static  List<SOAPElement> soap2List(Map<String,Object> map,String elementName) {
        List<SOAPElement> soapElementList=new ArrayList<>();
        Object obj=map.get(elementName);
        if(obj==null)return soapElementList;
        if(obj instanceof SOAPElement){
            SOAPElement picture= (SOAPElement) obj;
            soapElementList.add(picture);
        }else if(obj instanceof List){
            List<SOAPElement> pictures= (List<SOAPElement>) obj;
            soapElementList.addAll(pictures);
        }
        return soapElementList;
    }

    /**
     * 将 SOAPElement 中的元素若只有一个，则存储value值为单个的SOAPElement对象，若有多个相同的元素，则存储为 List<SOAPElement> 对象
     * @param soapElement
     * @param map
     */
    public static void serialXml(SOAPElement soapElement, Map<String,Object> map){
        String nodeName=soapElement.getNodeName();
        if(map.containsKey(nodeName)){
            List<SOAPElement> list=new ArrayList<>();
            list.add(soapElement);
            Object obj=map.get(nodeName);
            if(obj instanceof SOAPElement){
                SOAPElement origSOAPElement= (SOAPElement) map.get(nodeName);
                list.add(origSOAPElement);
            }else if(obj instanceof List){
                List<SOAPElement> origList= (List<SOAPElement>) map.get(nodeName);
                list.addAll(origList);
            }
            map.put(nodeName,list);
        }else{
            map.put(nodeName,soapElement);
        }
        Iterator iterator=soapElement.getChildElements();
        if(iterator.hasNext()){
            while (iterator.hasNext()){
                Object obj=iterator.next();
                if(obj instanceof SOAPElement){
                    SOAPElement childSoapElement= (SOAPElement) obj;
                    serialXml(childSoapElement,map);
                }
            }
        }
    }
}
